import React from 'react'
import { connect } from 'react-redux'
import { addTodo, setText } from '../actions/index'
class addTodoCom extends React.Component {
  constructor(props) {
    super(props)
  }
  changeText = (e) => { //输入框改变事件
    console.log(e.target.value)
    // 触发action中的方法
    this.props.setText(e.target.value)
  }
  addTodoItem = () => {
    // 触发actions中的添加方法
    this.props.addTodo(this.props.text);
    // 清空输入框
    this.props.setText('')
  }
  render () {
    let { text } = this.props;
    return (
      <div>
        <input value={text} onChange={this.changeText} />
        <button onClick={this.addTodoItem}>添加任务</button>
      </div>
    )
  }
}

let mapStateToProps = (state) => ({
  text: state.text
})

// 将添加todo的方法和设置输入框文本的方法都注入到props
let mapDispatchToProps = (dispatch) => ({
  addTodo: (text) => dispatch(addTodo(text)), //添加的actions
  setText: (text) => dispatch(setText(text)) //设置文本的actions
})
export default connect(mapStateToProps, mapDispatchToProps)(addTodoCom)